from core.ws_response import Text, Stop, WsObject

ALL_USERS = "users"

def reg(request):
    """chat login"""
    users = request.app(ALL_USERS, default=dict())
    name = request.param("ws_user")

    users[name] = User(request, name)
    print (list(users))
    return Text(data={"users":list(users), "func":"addUser"}, to=users.values())


def sendMsg(request):
    name = request.param("ws_user")

    data = request.get_data()
    rev_name = data["name"]

    users = request.app(ALL_USERS)
    to = users.values()

    if rev_name and rev_name in users:
        to = [users[rev_name], users[name]]
        
    return Text(data={"speaker": name, "message": data["message"], "func":"addMsg", "receiver": rev_name}, to=to)


def open(request):
    print "in open "

def close(request):
    users = request.app(ALL_USERS)
    name = request.param("ws_user")
    del users[name]

    if request.get_data:
        #click "logout" button
        return [Stop(), Text(data={"user": name , "func":"exit"}, to=users.values())]
    else:
        #closed by client directly
        return Text(data={"user": name , "func":"exit"}, to=users.values())


class User(WsObject):
    def __init__(self, request, name=None, content=None):
        WsObject.__init__(self, request)
        self.name = name
        self.content = content
        

